package com.eliza.library.device.usb

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.hardware.usb.UsbAccessory
import android.hardware.usb.UsbManager
import android.os.Build
import android.util.Log
import androidx.annotation.RequiresApi

@RequiresApi(Build.VERSION_CODES.TIRAMISU)
class USBUtils(val context: Context, val intent: Intent) {
    val usbManager: UsbManager = context.getSystemService(Context.USB_SERVICE) as UsbManager

    init {
        val accessory = intent.getParcelableExtra(
            UsbManager.EXTRA_ACCESSORY,
            UsbManager::class.java
        )!! as UsbAccessory
    }

    fun getList(): Array<out UsbAccessory> {
        val manager = context.getSystemService(Context.USB_SERVICE) as UsbManager
        val accessoryList: Array<out UsbAccessory> = manager.accessoryList
        for (usbAccessory in accessoryList) {
            Log.d("UsbAccessory", "getList: ${usbAccessory}")
        }
        return accessoryList
    }
}
//要明确获取权限，请先创建一个广播接收器。此接收器会监听在您调用 requestPermission() 时接收广播的 intent。


object USBTools {
    private const val ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION"

    private val usbReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            if (ACTION_USB_PERMISSION == intent.action) {
                synchronized(this) {
                    val accessory: UsbAccessory? =
                        intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY)

                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        accessory?.apply {
                            // call method to set up accessory communication
                        }
                    } else {
                        Log.d("TAG", "permission denied for accessory $accessory")
                    }
                }
            }
        }
    }
}
